//入口函数
$(function(){
  getShow();
})

var dataAll = [];

$(".add").click(function(){
  var user = $(".user").val();
  var phone = $(".phone").val();
  var ping = $(".ping").val();

  if(!user || !phone){
    alert("请完善信息")
    return;
  }
  
  $.post("/add",{user,phone,ping,time:getTime()},function(res){
    if(res.code == 200){
      getShow();
      $(".user").val("");
      $(".phone").val("");
      $(".ping").val("");
    }else{
      alert(res.msg)
    }
  })
})

function getShow(){
  $.get("/show",function(res){
    if(res.code == 200){
      show(res.info);
      dataAll = res.info;
    }else{
      alert(res.msg)
    }
  })
}


function show(arr){
  var str = "";
  $.each(arr,function(i,n){
    str += `
    <li>
    <div>姓名:${n.user}</div>
    <div>手机号:${n.phone}</div>
    <div>评价:
      <img src="/images/${n.ping>0?"1":"0"}.png" >
      <img src="/images/${n.ping>1?"1":"0"}.png" >
      <img src="/images/${n.ping>2?"1":"0"}.png" >
      <img src="/images/${n.ping>3?"1":"0"}.png" >
      <img src="/images/${n.ping>4?"1":"0"}.png" >
    </div>
    <div>上传时间:${n.time}</div>
    <button type="button" ${i?"":"disabled"} onclick="move(this,'${n._id}')">上移</button>
    <button type="button"  onclick="del('${n._id}')">删除</button>
    <button type="button"${i == arr.length - 1?"disabled":""} onclick="move(this,'${n._id}')">下移</button>
  </li>
    `;
  })
  $("ol").html(str);
}

function getTime(){
  var d = new Date();
  return d.getFullYear()+'-'+
       numFn(d.getMonth()+1)   +'-'+
       numFn(d.getDate())     +' '+
       numFn(d.getHours())   +':'+
       numFn(d.getMinutes())   +':'+
       numFn(d.getSeconds())   
}

function numFn(num){
  return num<10?"0"+num:num;
}


function del(id){
  if(confirm("确定要删除吗?")){
    $.get("/del",{id},function(res){
        if(res.code == 200){
          getShow()
          $(".tip").show();
          setTimeout(()=>{$(".tip").hide()},2000)
        }else{
          alert(res.msg)
        }
      })
  }
}
function move(self,id){
  var index = dataAll.findIndex(function(item){
    return item._id == id;
  })
  var obj = dataAll[index];
  if($(self).html() == "上移"){
    dataAll[index] = dataAll[index-1];
    dataAll[index-1] = obj;
  }else{
    dataAll[index] = dataAll[index+1];
    dataAll[index+1] = obj;
  }
  show(dataAll);
}
